(function(window)
{
  if(window.location.search.substr(1) == 'sauce')
  {
    // https://docs.saucelabs.com/reference/rest-api/#start-js-unit-tests
    function convertToSauceGlobalTestResult(results, duration)
    {
      var tests = Object.keys(results)
        .map(function(fullName)
        {
          return {
            'name'     : fullName,
            'result'   : results[fullName]['state'] == 'success',
            'message'  : results[fullName]['messages'].join('\n'),
            'duration' : duration['test'][fullName]
          };
        })
        .sort(function(a, b)
        {
          return a.name.localeCompare(b.name);
        });
    
      return {
        'passed' : qx.lang.Array.sum(tests.map(function(test)
        {
          return test['result'];
        })),
        'failed' : qx.lang.Array.sum(tests.map(function(test)
        {
          return !test['result'];
        })),
        'total'    : tests.length,
        'duration' : duration['total'],
        'tests'    : tests
      };
    };
  
    qx.event.Registration.addListener(window, 'ready', function()
    {
      var runner   = qx.core.Init.getApplication().runner;
      var duration = {
        'total' : Date.now(),
        'test'  : {}  
      };
      runner.addListener('changeTestSuiteState', function(event)
      {
        var state = event.getData();
        if(state == 'ready')
        {
          runner.addListener('changeTestCount', function(event)
          {
            // Can't use testModel changeState event, because 'start' is not always fired
            // and what fired it leads to very small inaccurate timings.
            duration['test'][runner.currentTestData.fullName] = Date.now();
          });  
          runner.testList.forEach(function(test)
          {
            test.addListener('changeState', function(event)
            {
              var state = event.getData();
              var name  = event.getTarget().fullName;
              if(state in {'success':0, 'failure':0})
              {
                duration['test'][name] = (Date.now() - duration['test'][name]) / 1000;
                test.removeListener('changeState', arguments.callee);                
              }
            });
          });
          runner.view.run();
        }
        else if(state == 'finished')
        {
          duration['total'] = (Date.now() - duration['total']) / 1000;
          window.global_test_results = convertToSauceGlobalTestResult(runner.view.getTestResults(), duration);
        }
      });
    });
  }
})(window);